<template>
  <div class="container">
    <nav-bar @setCurrentType="setCurrentType" />
    <!-- 骨架屏 -->
    <sk-list :top="82" v-if="isSkLoading" />
    <news-list :newsData="newsList" :top="82" v-show="!isSkLoading" />
  </div>
</template>

<script lang="ts">
import { ComputedRef, defineComponent, onMounted, ref, watch } from "vue";
import { Store, useStore } from "vuex";
import { useNavType, useNewsList } from "../compositions";
import { INewsInfo, NAV_TYPES } from "../typings";

import NavBar from "../components/NavBar/index.vue";
import NewsList from "../components/NewsList/index.vue";
import SkList from "../components/Skeleton/index.vue";

// defineComponent是ts类型推断
export default defineComponent({
  name: "Home",
  components: { NavBar, NewsList, SkList },
  setup() {
    const store: Store<any> = useStore();

    //返回列表数据
    const newsList: ComputedRef<INewsInfo[]> = useNewsList(store);

    // console.log(newsList.value);
    //打印Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}, 6: {…}, 7: {…}, 8: {…}, 9: {…}}

    //返回一个更改类型的方法, 给navBar点击用的
    const setCurrentType: (type: NAV_TYPES) => ComputedRef<INewsInfo[]> =
      useNavType(store);

    //骨架屏显示与否的变量
    const isSkLoading = ref<boolean>(true);

    //首次组件页面加载时2秒后隐藏骨架屏(默认首次加载显示)
    onMounted(() => {
      setTimeout(() => {
        isSkLoading.value = false;
      }, 2000);
    });

    //每次切换nav-item也要加载显示骨架屏
    watch(
      () => {
        //监控currentType变化
        return store.state.home.currentType;
      },
      () => {
        //监控到切换了就显示
        isSkLoading.value = true;

        //然后2秒后隐藏
        setTimeout(() => {
          isSkLoading.value = false;
        }, 2000);
      }
    );

    return {
      newsList,
      setCurrentType,
      isSkLoading,
    };
  },
});
</script>

